package org.changs.monitor;

import android.Manifest;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.WindowManager;

import com.tbruyelle.rxpermissions2.RxPermissions;

import org.changs.aplug.base.BaseActivity;
import org.changs.monitor.camera.CameraTaskManager;
import org.changs.monitor.helper.ShakeHelper2;

import javax.inject.Inject;

public class MainActivity extends BaseActivity implements Runnable {

    @Inject CameraTaskManager mCameraTaskManager;
    private Handler mHandler = new Handler();
    private ShakeHelper2 mShakeHelper2;


    @Override
    public void setup(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

        new RxPermissions(this)
                .request(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO)
                .subscribe(aBoolean -> {
                    if (aBoolean)
                        replace(new Test1Fragment(), false);
                    else
                        onError("请先赋予应用权限");
                });

        int a = 1;
        switch (a) {
            case 1:
                System.out.println(1);
                break;
            default:
                System.out.println("a = " + a);
                break;
        }

        mShakeHelper2 = new ShakeHelper2(this, () -> {
            mCameraTaskManager.takePicture("0");
        });
        mShakeHelper2.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (!isFinishing()) finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(this);
        mCameraTaskManager.closeAll();
        mShakeHelper2.pause();
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public void replace(Fragment fragment, boolean addToBackStack) {
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fl_container, fragment);
        if (addToBackStack)
            transaction.addToBackStack(null);
        transaction.commitAllowingStateLoss();
    }

    @Override
    public void run() {
        showMessage("正在切换视频文件!");
        mCameraTaskManager.takePicture("0");
        mHandler.postDelayed(this, 60 * 1000);
    }

    public void nextFile(View view) {
        mCameraTaskManager.nextFile();
    }

    public void takePicture(View view) {
        mCameraTaskManager.takePicture("0");
    }
}
